// router
import {createRouter, createWebHistory} from "vue-router";
import {PATH_URL, PATH_URL_LOGIN, TOKEN_KEY, WHITE_PATH} from "/@/assets/constant.js";

const routerList = [
    {
        path: PATH_URL,
        name: 'view',
        component: () => import('/src/view/index.vue'),
        children: [
            // 默认显示，需要配置运行时编译
            {
                path: PATH_URL + '/',       // 这里需要配置一个/，因为后台配置的是/view/*path，会导致/，不被适配，因此需要加上
                name: 'index',
                component: {
                    template: `
                    <div>
                        <h1>欢迎访问后端管理</h1>
                    </div>
                    `
                }
            },
            {
                path: PATH_URL + '/client',
                name: 'client',
                component: () => import('/src/components/client.vue'),
            },
            {
                path: PATH_URL + '/user',
                name: 'user',
                component: () => import('/src/components/user.vue'),
            }, {
                path: PATH_URL + '/scope',
                name: 'scope',
                component: () => import('/src/components/scope.vue'),
            }
        ]
    },
    {
        path: PATH_URL + '/login',
        name: 'login',
        component: () => import('/src/view/login.vue'),
    },
    // 其它所有页面，都404
    {
        path: PATH_URL + '/404',
        name: '404',
        component: () => import('/src/view/404.vue')
    },
    {
        path: PATH_URL + '/:pathMatch(.*)',
        redirect: PATH_URL + "/404"
    }
]

// 创建路由
const router = createRouter({
    routes: routerList,
    history: createWebHistory(),
})

// 路由守卫
router.beforeEach((to, from, next) => {
    const token = localStorage.getItem(TOKEN_KEY);
    // 如果访问的是登录页，且没有登录过
    if (WHITE_PATH.indexOf(to.path) !== -1) { // 如果在白名单中，直接放行
        next()
    } else {
        if (token) { // 如果有 token，表示已经登录，放行
            next()
        } else { // 否则跳转到登录页
            next(PATH_URL_LOGIN)
        }
    }
})

export default router
